import config from '../config.js'

import utils from './index.js'
import dlg from './dialogs.js'
import signMd5Utils from './signMd5Utils.js'

const rootUrl = config.rootUrl;

const request = async (p) => {

	//当前的 token
	let token = utils.getLoginToken();

	//传入的参数
	let {
		method,
		url,
		dataType,
		data,
		header,

		loading,
		fail,
		success,
	} = {
		url: '',
		dataType: 'json',
		data: {},
		loading: true,
		fail: false,
		success: false,
		header: {
			'X-Access-Token': token
		},
		...p,
	};

	// debug 用
	console.log({
		url,

		method,
		header,

		dataType,
		data,

		loading,

		fail,
		success,
	})

	let sign = signMd5Utils.getSign(url, data);
	let signHeader = {
		"X-Sign": sign,
		"X-TIMESTAMP": signMd5Utils.getTimestamp()
	};


	//显示 loading
	if (loading === true) {
		uni.showLoading({
			title: '处理中',
			mask: true
		})
	}

	//api 请求响应
	let response = {};

	try {
		//传入接口调用 key
		data = {
			...data,

			__invoke_key: getApp().globalData.invoke_key,
			__app_name: getApp().globalData?.app_name,
			__user_id: getApp().globalData?.userInfo?.userid,
		}

		//发起请求
		const ir = await uni.request({
			method,
			url: url.toLowerCase().startsWith('http') ? url : rootUrl + url,
			dataType,
			header: {
				...header,
				...signHeader
			},
			data
		});

		console.log(100, {
			ir
		})

		//分析调用结果
		if (ir.statusCode !== 200) {
			response = {
				err: {
					errMsg: `调用接口返回状态码${ir.statusCode}`
				}
			}
		} else if (typeof(ir.data) !== 'object' || ir.data.code === undefined ||
			ir.data.message === undefined || ir.data.result === undefined) {
			response = {
				err: {
					errMsg: `调用接口返回数据格式不正确`
				}
			}
		} else if (ir.data.code != 0) {
			response = {
				err: {
					errMsg: ir.data.message || '调用接口返回错误(E0001)'
				}
			}
		} else {
			response = {
				res: {
					data: ir.data.result,
					token: ir.data.token
				}
			}
		}
	} catch (err) {

		console.log(300, {
			err
		})

		err.errMsg = err.errMsg || err.message || '调用接口返回错误(E0002)'
		err.errMsg = err.errMsg.startsWith('request:fail') ? (err.message || "网络请求错误") : err.errMsg

		response = {
			err
		}
	} finally {
		if (loading === true) {
			uni.hideLoading();
		}
	}

	console.log(20, {
		response
	})

	//使用调用结果
	const {
		err,
		res
	} = response;

	if (err) {

		if (fail !== false) {
			fail({
				errMsg: err.errMsg
			});
		} else {
			dlg.showError(err.errMsg);
		}

	} else {
		if (success !== false) {
			success(res)
		} else {

			// save new token
			if (res.token) {
				utils.saveLoginToken(res.token)
			}

			return res.data;
		}
	}

}

export default {
	get: async (p) => {
		return await request({
			...p,
			method: 'GET'
		});
	},
	post: async (p) => {
		return await request({
			...p,
			method: 'POST'
		});
	},
	put: async (p) => {
		return await request({
			...p,
			method: 'PUT'
		});
	}
}